<template>
  <div style="margin-top: 2%; margin-left: 2%; margin-right: 2%;">
    <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px" height="10%">
      <el-row :gutter="150">
        <el-col :span="11">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号码" clearable :style="{width: '100%'}" @change="checkMobile" >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker v-model="form.birthday" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :style="{width: '100%'}" 
                  placeholder="请选择日期选择" clearable>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="11">
           <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex" >
                  <el-radio v-for="item in dict.type.sex" :key="item.value" :label="item.value">
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
            </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="会员卡号" prop="userNo" v-if="form.userNo!== null && form.userNo!== ''">
                <el-input v-model="form.userNo" placeholder="请输入会员号" disabled clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="车牌号" prop="carNo">
                <el-input v-model="form.carNo" placeholder="请输入车牌号" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="备注信息" prop="description">
                <el-input v-model="form.description" placeholder="请输入备注信息" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
        <div style="margin-top: 1%; margin-left: 2%; margin-right: 10%;">
          <el-divider content-position="center" >会员卡券信息</el-divider>
        </div>
      

      <el-row  :gutter="150">
        <!-- <el-col :span="24">
          <el-form-item label="卡类型" prop="type" >
            <el-radio-group v-model="form.userCoupon.type" @change="handleRadioChange">
              <el-radio v-for="item in dict.type.tm_coupon_type" :key="item.value" :label="item.value">
                  {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col> -->
          <el-col :span="11">
            <el-form-item label="办卡时间" prop="openTime">
              <el-date-picker v-model="form.userCoupon.openTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    :clearable="false"
                    :style="{width: '100%'}" 
                    placeholder="请选择日期选择" >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
              <el-form-item label="卡项名称" prop="userCoupon.couponId">
                <el-select v-model="form.userCoupon.couponId" placeholder="请选择" @change="getCouponInfo" style="width: 100%">
                  <el-option
                    v-for="item in form.coupons"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    <span style="float: left" :span="11">{{ item.label }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px;display: none" :span="11">{{ item.value }}</span>
                  </el-option>
                </el-select>
                  <!-- <el-input v-model="form.userCoupon.name" placeholder="如:10次xxx卡" /> -->
              </el-form-item>
          </el-col>
      </el-row>
      <el-row  :gutter="150">
          <el-col :span="11">
              <el-form-item label="充值金额" prop="amount">
                  <el-input v-model="form.userCoupon.amount" placeholder="请输充值金额" @input="handleInput" disabled/>
              </el-form-item>
          </el-col>
          <!-- <el-col :span="11">
              <el-form-item label="赠送金额" prop="giveMoney" v-if="form.userCoupon.type === 'P'">
                  <el-input v-model="form.userCoupon.giveMoney" placeholder="请输入赠送金额" @input="handleInput"/>
                  </el-form-item>
          </el-col>
          <el-col :span="11">
              <el-form-item label="可用金额" prop="usableMoney" v-if="form.userCoupon.type === 'P'">
                  <el-input v-model="form.userCoupon.usableMoney" placeholder="自动计算" disabled/>
              </el-form-item>
          </el-col>
          <el-col :span="11">
              <el-form-item label="次数" prop="usableTime" v-if="form.userCoupon.type === 'T'">
                  <el-input v-model="form.userCoupon.usableTime" placeholder="请输入次数"/>
              </el-form-item>
          </el-col> -->
          <el-col :span="11" >
              <el-form-item label="赠送金额" prop="giveMoney" v-show="form.userCoupon.type === 'P'">
                  <el-input v-model="form.userCoupon.giveMoney"  placeholder="请输入内容" disabled/>
              </el-form-item>
          </el-col>
      </el-row>
      <el-row  :gutter="150">
          <el-col :span="11">
              <el-form-item label="可用余额/次数" prop="balance">
                  <el-input v-model="form.userCoupon.balance"  placeholder="请输入内容" disabled/>
              </el-form-item>
          </el-col>
          <el-col :span="11">
              <el-form-item label="实收金额" prop="userCoupon.receiveMoney">
                  <el-input v-model="form.userCoupon.receiveMoney"  placeholder="请输入内容" />
              </el-form-item>
          </el-col>
      </el-row>

      <el-form-item size="large" style="float: right; margin-right: 7%;">
        <el-button type="primary" @click="submitForm" >确定收银</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>
<script>
import { listCoupon, getCoupon } from "@/api/backendApi/coupon";
import { updateMember, addMember } from "@/api/backendApi/member";
import request from '@/utils/request';
// import Decimal from "@/api/common/decimal.js";
export default {
  components: {},
  props: [],
  dicts: ['sex','tm_coupon_type'],
  data() {
    return {
      form: {
        id: null,
        mobile: null,
        groupId: null,
        userNo: null,
        avatar: null,
        name: null,
        openId: null,
        idcard: null,
        gradeId: null,
        startTime: null,
        endTime: null,
        balance: null,
        point: null,
        sex: '1',
        birthday: null,
        carNo: null,
        source: null,
        password: null,
        salt: null,
        address: null,
        merchantId: null,
        storeId: null,
        isStaff: null,
        createTime: null,
        updateTime: null,
        status: null,
        description: null,
        operator: null,
        coupons: [],
        userCoupon: {
          type: null,
          amount: null,
          giveMoney: null,
          openTime: new Date(),
          couponId: '',
          balance: null,
          receiveMoney: null
        }
      },
      rules: {
        'userCoupon.receiveMoney': [
          { required: true, message: "实收金额不能为空", trigger: "blur" },
          {
            pattern: /^(?!0\d)\d{1,7}(\.\d{1,2})?$/,
            message: '数字长度不超过7位，小数位数不超过2位,不可为负',
            trigger: 'blur'
          }
        ],
        'userCoupon.couponId': [
          { required: true, message: "卡项不能为空", trigger: "blur" }
        ],
         name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误',
            trigger: 'blur'
          },
          { validator: this.validateUsername, trigger: 'submit' }
        ],
      },
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getCoupons();
  },
  mounted() {},
  methods: {
    //核对手机号
    async checkMobile(){
      console.log('核对')
      await this.$refs.form.validateField('mobile');
    },
    async validateUsername(rule, value, callback) {
      console.log('校验',value)
      if (!value) {
        callback();
        return;
      }
      try {
        // 假设调用后端接口进行验证，例如使用 axios 发送请求
        console.log('例如使用 axios 发送请求')
        const response = await request.get('backendApi/member/list', { params: { mobile: value } });
        console.log('response',response)
        if (response.total != 0) {
          callback(new Error('手机号已存在，请重新输入'));
        } else {
          callback();
        }
      } catch (error) {
        callback(new Error('验证过程中出现错误，请稍后重试'));
      }
    },
    //点击卡项名称填充金额
    getCouponInfo(id){
      getCoupon(id).then(response =>{
        this.form.userCoupon.type=response.data.type;
        if(response.data.type === 'T'){
          this.form.userCoupon.amount=response.data.amount;
          this.form.userCoupon.receiveMoney=response.data.amount;
          this.form.userCoupon.balance=response.data.usableMoney;
        }else{
          this.form.userCoupon.amount=response.data.amount;
          this.form.userCoupon.receiveMoney=response.data.amount;
          this.form.userCoupon.giveMoney=response.data.giveMoney;
          this.form.userCoupon.balance=response.data.usableMoney;
        }
        console.log(response)  
      }
      )
    },
    // 查询卡列表
    getCoupons() {
      this.loading = true;
      listCoupon().then(response => {
        for(let item of response.rows){
          var coupon = {
          "value": null,
          "label": null
        }
          coupon.label=item.name;
          coupon.value=item.id;
          this.form.coupons.push(coupon)
        }
      });
    },
    /** 储值卡根据充值金额和赠送金额计算可用金额 */
    handleInput(event) {
        if(this.form.userCoupon.type === 'P'){
            this.form.userCoupon.usableMoney='';
            const num1 = this.form.userCoupon.amount ? new Decimal(this.form.userCoupon.amount): new Decimal(0);
            const num2 = this.form.userCoupon.giveMoney ? new Decimal(this.form.userCoupon.giveMoney): new Decimal(0);
            const result = num1.add(num2).toNumber();
            this.form.userCoupon.usableMoney = result;
        }
    },
    /** 切换选项清空数据 */
     handleRadioChange(newValue) {
      this.reset();
      if (newValue === 'P') {
        this.form.userCoupon.type='P'
      }else{
        this.form.userCoupon.type='T'
      }
    },
    /** 提交按钮 */
    async submitForm() {
      
      await this.$refs["form"].validate(valid => {
        try {
        if (valid) {
          if (this.form.id != null) {
            updateMember(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMember(this.form).then(response => {
              console.log(response)
              if(response.code === 200){
                this.$modal.msgSuccess("开卡成功");
                // this.$router.push({ path: '/member' });
                window.location.href = this.$router.resolve({path: '/member'}).href;
              }else{
                this.$modal.msgSuccess("开卡失败");
              }
            });
          }
        }
        } catch (e) {
        console.error('表单验证过程中出现错误', e);
      }
      });
    },
    resetForm() {
      // this.$refs['elForm'].resetFields()
      this.$router.push({ path: '/member' });
    },
  }
}

</script>

